Imports TAPI3Lib
Imports System.IO
Imports System.Diagnostics
Imports System.Text.RegularExpressions


Public Class frmMain

#Region "Class Definition"

   Inherits System.Windows.Forms.Form

   Private WithEvents myTAPI As VBTAPI
   Private MyAddress As String
   Private SystemConfig As New MyDictionary
   Private UserConfig As New MyDictionary
#End Region

#Region " Windows Form Designer generated code "

   Public Sub New()
      MyBase.New()

      'This call is required by the Windows Form Designer.
      InitializeComponent()

      'Add any initialization after the InitializeComponent() call

   End Sub

   'Form overrides dispose to clean up the component list.
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      If Not myTAPI Is Nothing Then myTAPI.Dispose()
      MyBase.Dispose(disposing)
   End Sub

   'Required by the Windows Form Designer
   Private components As System.ComponentModel.IContainer

   'NOTE: The following procedure is required by the Windows Form Designer
   'It can be modified using the Windows Form Designer.  
   'Do not modify it using the code editor.
   Friend WithEvents statusBar As System.Windows.Forms.StatusBar
   Friend WithEvents NotifyIcon As System.Windows.Forms.NotifyIcon
   Friend WithEvents TabPage1 As System.Windows.Forms.TabPage
   Friend WithEvents TabPage2 As System.Windows.Forms.TabPage
   Friend WithEvents btnSaveConfig As System.Windows.Forms.Button
   Friend WithEvents Label2 As System.Windows.Forms.Label
   Friend WithEvents ddLineAddress As System.Windows.Forms.ComboBox
   Friend WithEvents lblNumber As System.Windows.Forms.Label
   Friend WithEvents lblName As System.Windows.Forms.Label
   Friend WithEvents TabSet As System.Windows.Forms.TabControl
   Friend WithEvents ttNotifyIcon As System.Windows.Forms.ToolTip
   Friend WithEvents Label1 As System.Windows.Forms.Label
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      Me.components = New System.ComponentModel.Container
      Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMain))
      Me.statusBar = New System.Windows.Forms.StatusBar
      Me.NotifyIcon = New System.Windows.Forms.NotifyIcon(Me.components)
      Me.TabSet = New System.Windows.Forms.TabControl
      Me.TabPage1 = New System.Windows.Forms.TabPage
      Me.Label1 = New System.Windows.Forms.Label
      Me.lblName = New System.Windows.Forms.Label
      Me.lblNumber = New System.Windows.Forms.Label
      Me.TabPage2 = New System.Windows.Forms.TabPage
      Me.btnSaveConfig = New System.Windows.Forms.Button
      Me.Label2 = New System.Windows.Forms.Label
      Me.ddLineAddress = New System.Windows.Forms.ComboBox
      Me.ttNotifyIcon = New System.Windows.Forms.ToolTip(Me.components)
      Me.TabSet.SuspendLayout()
      Me.TabPage1.SuspendLayout()
      Me.TabPage2.SuspendLayout()
      Me.SuspendLayout()
      '
      'statusBar
      '
      Me.statusBar.Location = New System.Drawing.Point(0, 121)
      Me.statusBar.Name = "statusBar"
      Me.statusBar.Size = New System.Drawing.Size(370, 22)
      Me.statusBar.TabIndex = 6
      '
      'NotifyIcon
      '
      Me.NotifyIcon.Icon = CType(resources.GetObject("NotifyIcon.Icon"), System.Drawing.Icon)
      Me.NotifyIcon.Text = "TAPI"
      Me.NotifyIcon.Visible = True
      '
      'TabSet
      '
      Me.TabSet.Controls.Add(Me.TabPage1)
      Me.TabSet.Controls.Add(Me.TabPage2)
      Me.TabSet.Dock = System.Windows.Forms.DockStyle.Fill
      Me.TabSet.Location = New System.Drawing.Point(0, 0)
      Me.TabSet.Name = "TabSet"
      Me.TabSet.SelectedIndex = 0
      Me.TabSet.Size = New System.Drawing.Size(370, 121)
      Me.TabSet.TabIndex = 8
      '
      'TabPage1
      '
      Me.TabPage1.Controls.Add(Me.Label1)
      Me.TabPage1.Controls.Add(Me.lblName)
      Me.TabPage1.Controls.Add(Me.lblNumber)
      Me.TabPage1.Location = New System.Drawing.Point(4, 22)
      Me.TabPage1.Name = "TabPage1"
      Me.TabPage1.Size = New System.Drawing.Size(362, 95)
      Me.TabPage1.TabIndex = 0
      Me.TabPage1.Text = "Call Info"
      '
      'Label1
      '
      Me.Label1.Location = New System.Drawing.Point(16, 10)
      Me.Label1.Name = "Label1"
      Me.Label1.Size = New System.Drawing.Size(176, 16)
      Me.Label1.TabIndex = 4
      Me.Label1.Text = "Last Call"
      '
      'lblName
      '
      Me.lblName.BackColor = System.Drawing.SystemColors.Info
      Me.lblName.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblName.Location = New System.Drawing.Point(16, 64)
      Me.lblName.Name = "lblName"
      Me.lblName.Size = New System.Drawing.Size(320, 24)
      Me.lblName.TabIndex = 2
      '
      'lblNumber
      '
      Me.lblNumber.BackColor = System.Drawing.SystemColors.Info
      Me.lblNumber.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblNumber.Location = New System.Drawing.Point(16, 32)
      Me.lblNumber.Name = "lblNumber"
      Me.lblNumber.Size = New System.Drawing.Size(320, 24)
      Me.lblNumber.TabIndex = 1
      '
      'TabPage2
      '
      Me.TabPage2.Controls.Add(Me.btnSaveConfig)
      Me.TabPage2.Controls.Add(Me.Label2)
      Me.TabPage2.Controls.Add(Me.ddLineAddress)
      Me.TabPage2.Location = New System.Drawing.Point(4, 22)
      Me.TabPage2.Name = "TabPage2"
      Me.TabPage2.Size = New System.Drawing.Size(362, 95)
      Me.TabPage2.TabIndex = 1
      Me.TabPage2.Text = "Config"
      '
      'btnSaveConfig
      '
      Me.btnSaveConfig.Location = New System.Drawing.Point(248, 64)
      Me.btnSaveConfig.Name = "btnSaveConfig"
      Me.btnSaveConfig.Size = New System.Drawing.Size(104, 24)
      Me.btnSaveConfig.TabIndex = 10
      Me.btnSaveConfig.Text = "Save Config"
      '
      'Label2
      '
      Me.Label2.Location = New System.Drawing.Point(8, 10)
      Me.Label2.Name = "Label2"
      Me.Label2.Size = New System.Drawing.Size(72, 16)
      Me.Label2.TabIndex = 9
      Me.Label2.Text = "Line Address"
      '
      'ddLineAddress
      '
      Me.ddLineAddress.Location = New System.Drawing.Point(80, 8)
      Me.ddLineAddress.MaxDropDownItems = 50
      Me.ddLineAddress.Name = "ddLineAddress"
      Me.ddLineAddress.Size = New System.Drawing.Size(280, 21)
      Me.ddLineAddress.Sorted = True
      Me.ddLineAddress.TabIndex = 8
      '
      'frmMain
      '
      Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
      Me.ClientSize = New System.Drawing.Size(370, 143)
      Me.Controls.Add(Me.TabSet)
      Me.Controls.Add(Me.statusBar)
      Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
      Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
      Me.MaximizeBox = False
      Me.Name = "frmMain"
      Me.ShowInTaskbar = False
      Me.Text = "TAPI4CTI"
      Me.TabSet.ResumeLayout(False)
      Me.TabPage1.ResumeLayout(False)
      Me.TabPage2.ResumeLayout(False)
      Me.ResumeLayout(False)

   End Sub

#End Region


#Region "Initialisation"
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

      ' Control settings
      Control.CheckForIllegalCrossThreadCalls = False

      ' Ensure directory is known
      Directory.SetCurrentDirectory(Application.StartupPath)

      ' Ensure .NET is installed
      If Not DOTNETDetect.IsInstalled Then
         MsgBox("This program requires the .NET Framework to be installed", MsgBoxStyle.Critical, ".NET Framework Required")
         Me.Close()
         Application.Exit()
         End
      End If

      Try
         SetStatus("Loading system.ini...")
         SystemConfig.LoadINI("system.ini")
         If SystemConfig("CALLS.PATH") = "" Then SystemConfig("CALLS.PATH") = "C:\calls.xml"
         SetStatus("Loading user.ini...")
         UserConfig.LoadINI("user.ini")
         MyAddress = UserConfig("LINE.ADDRESS")
      Catch ex As Exception
         MsgBox("Unable to load configuration ini file: " + ex.Message, MsgBoxStyle.Exclamation, "Error")
      End Try

      Try
         SetStatus("Initializing TAPI...")
         myTAPI = New VBTAPI
         LoadAvailableAddressLines(True)
         If MyAddress <> "" Then
            GoOnline()
            WindowState = FormWindowState.Minimized
         Else
            MsgBox("Please set the line address", MsgBoxStyle.Information, "Line Address")
            TabSet.SelectedTab = TabSet.TabPages(1)
         End If
      Catch ex As Exception
         MsgBox("Error initializing TAPI: " & ex.Message, MsgBoxStyle.Critical, "Error")
      End Try

   End Sub
#End Region

#Region "Call Notification Events"

   Private Sub Incoming(ByVal CallNotification As ITCallNotificationEvent) Handles myTAPI.IncomingCall

      Dim CallerNumber As String = CallNotification.Call.CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER)
      Dim CallerName As String = CallNotification.Call.CallInfoString(CALLINFO_STRING.CIS_CALLERIDNAME)

      lblNumber.Text = CallerNumber
      lblName.Text = CallerName

      If InStr(MyAddress, "(" & CallerNumber & ")") = 0 Then
         ' Incoming call
         'NotifyIcon.ShowBalloonTip(3000, "Incoming Call", String.Format("Incoming call from %1 (%2)", CallerNumber, CallerName), ToolTipIcon.Info)
         SaveToFile(SystemConfig("CALLS.PATH"), "<calls><call><number>" & CallerNumber & "</number></call></calls>")
      End If

   End Sub
#End Region

#Region "TAPI Functions"

   Private Sub LoadAvailableAddressLines(ByVal ChooseDefault As Boolean)

      ' Clear listbox
      ddLineAddress.Items.Clear()

      ' Populate anew
      Dim AddressCollection As ITCollection = myTAPI.oTAPI.Addresses()
      For Each Address As ITAddress In AddressCollection ' looping through address collection
         'Debug.WriteLine(Address.AddressName)
         If Regex.IsMatch(Address.AddressName, SystemConfig("ADDRESS.INCLUDE")) Then
            If Not Regex.IsMatch(Address.AddressName, SystemConfig("ADDRESS.EXCLUDE")) Then
               'If InStr(Address.AddressName, Trim(Extension), CompareMethod.Text) Then
               ddLineAddress.Items.Add(Address.AddressName)
               'End If
            End If
         End If
      Next

      ' Choose default
      If ChooseDefault Then
         If ddLineAddress.Items.Count = 1 Then
            SaveLineAddress(CStr(ddLineAddress.Items(0)))
         End If
      End If

   End Sub

   Private Sub GoOnline()
      SetStatus("Registering line for call notifications......")
      myTAPI.ChangeLine(MyAddress)
      ddLineAddress.Text = MyAddress
      SetStatus("Online: " & MyAddress)
   End Sub

#End Region

#Region "Utility Functions"

   Sub SetStatus(ByVal Msg As String)
      statusBar.Text = Msg
      NotifyIcon.Text = Msg
   End Sub
#End Region

#Region "Form Events"

   Private Sub frmMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.SizeChanged
      If WindowState = FormWindowState.Minimized Then
         Hide()
      Else
         Show()
      End If
   End Sub

   Private Sub btnSaveConfig_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveConfig.Click
      ' Save ini
      If ddLineAddress.Text <> "" Then
         SaveLineAddress(ddLineAddress.Text)
         GoOnline()
      Else
         MsgBox("Please select an address line", MsgBoxStyle.Exclamation, "Incomplete")
      End If
   End Sub

   Private Sub SaveLineAddress(ByVal LineAddress As String)
      MyAddress = LineAddress
      Try
         ' HACK: This could be better
         SaveToFile("user.ini", "LINE.ADDRESS=" & MyAddress)
      Catch ex As IOException
         MsgBox("Unable to save user.ini: " & ex.Message, MsgBoxStyle.Critical, "Error")
      Catch ex As Exception
         MsgBox("Error initializing TAPI: " & ex.Message, MsgBoxStyle.Critical, "Error")
      End Try
   End Sub

   Private Sub NotifyIcon1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon.Click
      If Me.WindowState = FormWindowState.Minimized Then
         Me.Show()
         Me.WindowState = FormWindowState.Normal
      Else
         'Me.WindowState = FormWindowState.Minimized
      End If
      'Show()
      Me.Activate()
   End Sub

   Private Sub frmMain_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
      NotifyIcon.Visible = False
   End Sub
#End Region

End Class
